package cn.varin;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.junit.jupiter.api.Test;

public class MqttSendMessageTest {



    /**
     *
     *
     * String serverURI,(mqtt服务端地址)
     * String clientId,(客户端id)
     * MqttClientPersistence persistence（内存持久类）
     *
     *
     */
    public static String serviceURL= "tcp://varin.cn:1883";
    public static String clientId="varya_test_01";
    public static MqttClient client;
    public static String user="varya";
   public static String password= "123456";

    static {
        try {
            // 建立一个mqqt客户端类
            client = new MqttClient(serviceURL,clientId,new MemoryPersistence());
            MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
            mqttConnectOptions.setUserName(user);
            mqttConnectOptions.setPassword(password.toCharArray());
            client.connect(mqttConnectOptions);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }


    // 发送消息
    @Test
    public void SendMessageTest() throws MqttException {
        // 设置消息
        String message = "hello mqttx Client";
        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        mqttMessage.setQos(2);
        // 当一个主题的消息设置了 setRetained(true) 后，这条消息会存储在 Broker 中。如果后续有新的客户端订阅这个主题，则无论何时订阅，都会立即收到最近的一条带有 retained 属性的消息作为初始数据2。如果没有设置 retained 或者之前的消息未被保留，则新订阅者不会接收到任何历史消息。,
        mqttMessage.setRetained(true);
        // 发送消息
        client.publish("java_and_mqttx_conn", mqttMessage);

        //发送完，关闭连接
        client.disconnect();
        client.close();


    }


}
